﻿using GZCH.Business;
using LitJson;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.SessionState;
using System.Xml;

namespace Web.FireAdmin.Phone.Controlers
{
    /// <summary>
    /// IndexAshx 的摘要说明
    /// </summary>
    public class IndexAshx : IHttpHandler, IRequiresSessionState
    {
        private HttpContext context;

        public void ProcessRequest(HttpContext context1)
        {          
            context = context1;

            if (HttpContext.Current.Session["LoginID"] == null)
            {
                context.Response.AddHeader("Content-Type", "text/html; charset=UTF-8");
                context.Response.Write("{\"code\":401,\"msg\":\"未登录\"}");
                context.Response.End();
                return;
            }

            string getType = context.Request.QueryString["flag"].ToString();

            switch (getType)
            {
                case "init":
                    init();
                    break;
            }
             
        }

        private void init()
        {
            string code = "0";
            string menu = BindList("6", "");
            if (menu == "[]")
                code = "0";
            string UserName = HttpContext.Current.Session["UserName"].ToString();
            string result = "{\"code\":\"" + code + "\",\"username\":\""+ UserName + "\",\"time\":\""+DateTime.Now.ToString()+"\",\"data\":" + menu + "}"; 

            context.Response.AddHeader("Content-Type", "text/html; charset=UTF-8");
            context.Response.Write(result);
            context.Response.End();
        }

        /// <summary>
        /// 获取菜单列表
        /// </summary>
        /// <param name="where"></param>
        protected string BindList(string RootId, string where)
        {
            DataSet ds = null;

            DataSet Pds = new frmMenuBLL().GetList(where);
            string sWhere = "";
            string role = HttpContext.Current.Session["UserRoles"].ToString().Replace("}{", "','").Replace("{", "'");
            if (role.Length - 2 < 0)
            {
                return "";
            }
            role = role.Substring(0, role.Length - 2);
            if (HttpContext.Current.Session["UserRoles"].ToString().IndexOf("SystemAdmin") > 0)
            {
                sWhere = "";
                ds = new frmMenuBLL().GetRoleList(sWhere, "1");
            }
            else
            {
                sWhere += " and fldRole in(" + role + ")";
                ds = new frmMenuBLL().GetRoleList(sWhere, "");
            }

            string menuListT = "";
            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                using (DataView dvTree = new DataView(Pds.Tables[0]))
                {
                    dvTree.RowFilter = "parentId ='" + RootId + "' and delflag='0'  ";

                    //删除没有权限的根菜单
                    int len = dvTree.Count - 1;
                    for (int i = len; i >= 0; i--)
                    {
                        string parentId = dvTree[i]["ID"].ToString();
                        string sel = string.Format("parentId='{0}'", parentId);
                        DataRow[] rs = ds.Tables[0].Select(sel);
                        if (rs == null || rs.Length <= 0)
                        {
                            dvTree.Delete(i);
                        }
                    }

                    string menu = "";
                    foreach (DataRowView view in dvTree)  //组建菜单
                    {
                        string parentID = view.Row.ItemArray[0].ToString();
                        string MainMenuName = view.Row.ItemArray[1].ToString();
                        string temp = getMenu(parentID, MainMenuName, ds);
                        menu += temp + ",";
                    }
                    if (menu != "")
                        menu = menu.Substring(0, menu.Length - 1);


                    menuListT = "[" + menu  + "]";
                }
            }

            return menuListT;
        }

        /// <summary>
        /// 组建子菜单
        /// </summary>
        /// <param name="parentID"></param>
        /// <param name="MainMenuName"></param>
        /// <returns></returns>
        public string getMenu(string parentID, string MainMenuName, DataSet ds)
        {
            DataTable dt = ds.Tables[0];  

           
            DataRow[] drs = dt.Select("parentId = '" + parentID + "' and delflag='0'  ");
            StringBuilder temp = new StringBuilder();
            foreach (DataRow dr in drs)  //组建子菜单
            {
                string color = "";
                string icon = "";
                GetMenuIcon(dr["MenuName"].ToString().Trim(), out color, out icon);
                string url = ResolveUrl1((dr["Url"] == null || dr["Url"] == DBNull.Value) ? "" : dr["Url"].ToString().Trim());

                string MenuName = dr["MenuName"].ToString();
                temp.Append("{");
                temp.AppendFormat("\"name\":\"{0}\",", MenuName);
                temp.AppendFormat("\"url\":\"{0}\",", url);
                temp.AppendFormat("\"icon\":\"{0}\",", icon);
                temp.AppendFormat("\"color\":\"{0}\"", color);
                temp.Append("},");
            }

            string menuList = temp.ToString();
            if (menuList != "")
                menuList = menuList.Substring(0, menuList.Length - 1);

            string color1 = "";
            string icon1 = "";
            GetMenuIcon(MainMenuName.Trim(), out color1, out icon1);
            string MainMenuTop = "{" + string.Format("\"name\":\"{0}\",\"icon\":\"{1}\",\"color\":\"{2}\",\"menuList\":[", MainMenuName,icon1 ,color1);

            return MainMenuTop + menuList + "]}";
        }

        public string ResolveUrl1(string relativeUrl)
        {
            if (relativeUrl == null) throw new ArgumentNullException("relativeUrl");

            if (relativeUrl.Length == 0 || relativeUrl[0] == '/' ||
                relativeUrl[0] == '\\') return relativeUrl;

            int idxOfScheme =
              relativeUrl.IndexOf(@"://", StringComparison.Ordinal);
            if (idxOfScheme != -1)
            {
                int idxOfQM = relativeUrl.IndexOf('?');
                if (idxOfQM == -1 || idxOfQM > idxOfScheme) return relativeUrl;
            }

            StringBuilder sbUrl = new StringBuilder();
            sbUrl.Append(HttpRuntime.AppDomainAppVirtualPath);
            if (sbUrl.Length == 0 || sbUrl[sbUrl.Length - 1] != '/') sbUrl.Append('/');

            // found question mark already? query string, do not touch!
            bool foundQM = false;
            bool foundSlash; // the latest char was a slash?
            if (relativeUrl.Length > 1
                && relativeUrl[0] == '~'
                && (relativeUrl[1] == '/' || relativeUrl[1] == '\\'))
            {
                relativeUrl = relativeUrl.Substring(2);
                foundSlash = true;
            }
            else foundSlash = false;
            foreach (char c in relativeUrl)
            {
                if (!foundQM)
                {
                    if (c == '?') foundQM = true;
                    else
                    {
                        if (c == '/' || c == '\\')
                        {
                            if (foundSlash) continue;
                            else
                            {
                                sbUrl.Append('/');
                                foundSlash = true;
                                continue;
                            }
                        }
                        else if (foundSlash) foundSlash = false;
                    }
                }
                sbUrl.Append(c);
            }

            return sbUrl.ToString();
        }

        /// <summary>
        /// 获取菜单图标和颜色
        /// </summary>
        /// <param name="MenuName"></param>
        /// <param name="color"></param>
        /// <param name="icon"></param>
        public void GetMenuIcon(string MenuName, out string color, out string icon)
        {
            color = "";
            icon = "";

            XmlDocument xmlDoc = new XmlDocument();
            try
            {
                string path = HttpContext.Current.Server.MapPath("/./XML/MenuIcon.xml");
                xmlDoc.Load(path);

                XmlNodeList xnl = xmlDoc.SelectSingleNode("Icon").ChildNodes;
                foreach (XmlNode node in xnl)
                {
                    XmlElement xmlelem = (XmlElement)node;
                    if (xmlelem.GetAttribute("name") == MenuName)
                    {
                        XmlNodeList childnodelist = node.ChildNodes;
                        foreach (XmlNode childnode in node)
                        {
                            if (childnode.Name == "Color")  //菜单颜色
                            {
                                color = childnode.InnerText;
                            }
                            if (childnode.Name == "Value")  //图标值
                            {
                                icon = childnode.InnerText;
                            }
                        }
                        return;
                    }
                }
            }
            catch(Exception e)
            {
                return;
            }
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}